<template>
  <div class="container">
    <el-row>
      <el-card shadow="never">
        <div slot="header">
          <el-form :inline="true" :model="searchForm" size="small">
            <el-form-item label="名称" class="el-search-item">
              <el-input v-model="searchForm.cname" placeholder="名称" clearable></el-input>
            </el-form-item>
			<el-form-item label="编码" class="el-search-item">
			  <el-input v-model="searchForm.cno" placeholder="编码" clearable></el-input>
			</el-form-item>
            <el-form-item class="el-search-item">
              <el-button type="success" plain icon="el-icon-search" @click="getDataList">查询</el-button>
            </el-form-item>
            <el-form-item class="el-search-item">
              <el-button v-if='hasPerm("product:category:add")' type="primary" plain icon="el-icon-plus" @click="openAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据表格 element ui-->
        <el-table :data="tableData" :height="tableHeight" style="width: 100%" row-key="categoryId" :tree-props="{children: 'children'}">
			<el-table-column label="名称" align="center" sortable>
				<template slot-scope="scope">
					<span v-if="scope.row.pathName!=null">{{scope.row.pathName}}{{scope.row.cname}}</span>
					<span v-else>{{scope.row.cname}}</span>
				</template>
			</el-table-column>
		  <el-table-column label="图片" align="center" sortable>
		  	<template slot-scope="scope">
				<img :src="scope.row.cimg" height="30px"/>
		  	</template>
		  </el-table-column>
          <el-table-column prop="cno" label="编码" align="center" sortable></el-table-column>
          <el-table-column prop="seq" label="排序" align="center" sortable></el-table-column>
          <el-table-column label="状态" align="center" sortable>
			  <template slot-scope="scope">
			    <span v-if="scope.row.status==1">激活</span>
				<span v-else>失效</span>
			  </template>
		  </el-table-column>
		  <!-- <el-table-column prop="msg" label="备注" align="center" sortable></el-table-column> -->
          <el-table-column v-if='hasPerm("product:category:list")' label="更多操作" align="center" width="250">
            <template slot-scope="scope">
              <el-button v-if='hasPerm("product:category:edit")' @click="openUpdate(scope.row)" size="mini" type="text" icon="el-icon-edit">编辑</el-button>
              <el-button v-if='hasPerm("product:category:del")' @click="deleteFun(scope.row)" size="mini" type="text" icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件
        <el-pagination style="padding:0;text-align: center;" background @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"
                       :current-page="pageNum" :page-sizes="[8, 15, 20]" :page-size="pageSize" :total="total">
        </el-pagination> -->
      </el-card>
      <!--新增对话框-->
	  <el-drawer :title="dialog.dialogTitle" :visible.sync="dialog.visible" :direction="dialog.direction" :size="dialog.size" :before-close="handleClose">
        <el-row class="drawer-table">
            <el-col :span="24">
				<el-form :rules="rules" ref="categoryForm" :model="categoryForm" size="small" label-width="80px">
				  <el-form-item label="上级分类">
				      <el-input @click.native="catSelectDialogShow" v-model="categoryForm.parentName" placeholder="选择上级分类" auto-complete="off"></el-input>
				  </el-form-item>
				  <el-form-item prop="cname" label="名称">
					<el-input v-model="categoryForm.cname" placeholder="请输入名称" auto-complete="off"></el-input>
				  </el-form-item>
				  <el-form-item prop="cno" label="编码">
					<el-input v-model="categoryForm.cno" placeholder="请输入编码" auto-complete="off"></el-input>
				  </el-form-item>
				  <el-form-item prop="cimg" label="标题图片">
					  <img class="user-img" :src="categoryForm.cimg" />
					  <el-dropdown-item @click.native="uploadFun('flagImg')"><i class="fa el-icon-upload"></i>上传</el-dropdown-item>
				  </el-form-item>
				  <el-form-item label="状态" prop="status">
					<el-radio-group v-model="categoryForm.status">
						<el-radio :label="1">激活</el-radio><el-radio :label="0">失效</el-radio>
					</el-radio-group>
				  </el-form-item>
				  <el-form-item prop="seq" label="排序">
					<el-input v-model="categoryForm.seq" placeholder="请输入排序" auto-complete="off"></el-input>
				  </el-form-item>
				  <el-form-item prop="msg" label="备注">
					<el-input :rows="8" resize="none" type="textarea" maxlength="120" v-model="categoryForm.msg" placeholder="请输入备注" auto-complete="off"></el-input>
				  </el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row class="drawer-footer">
		    <el-col :span="24">
				<el-button @click="dialog.visible = false" size="small">取 消</el-button>
				<el-button type="primary" @click="submitFun()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
			</el-col>
		</el-row>
      </el-drawer>
	  
	  <!-- 选择上級分类 -->
	  <el-dialog title="选择上级分类" :visible.sync="dialogTree.visible" width="25%" top="5%">
	      <el-tree :data="tableData" :props="dialogTree.treeProps" show-checkbox  check-strictly node-key="categoryId"
	               default-expand-all :default-checked-keys="dialogTree.defKeys" ref="gcTreeRef" @check-change="catHandleNodeClick"
	               empty-text="加载中，请稍后..." style="height: 55vh;overflow: auto;"></el-tree>
	      <span slot="footer" class="dialog-footer">
	          <el-button @click="dialogTree.visible = false" size="small">取 消</el-button>
	          <el-button type="primary" @click="dialogTree.visible = false" size="small">确 定</el-button>
	      </span>
	  </el-dialog>
	  
	  <!-- 剪裁组件弹窗  标题图片 -->
	  <el-dialog title="上传标题图片" :visible.sync="dialogImage.cropperModel" width="850px">
	      <CropperImage :Name="dialogImage.cropperName" @uploadImgSuccess = "handleUploadSuccess" ref="child"></CropperImage>
	  </el-dialog>
	  
    </el-row>
  </div>
</template>
<script>
import CropperImage from "@/components/cropper/CropperImage";
import category from "@/api/product/category";
  export default {
	components: { CropperImage },
    data() {
      return {
        // 表格数据
        tableData: [],
        // 分页数据
        total: 0,
        pageNum: 1,
        pageSize: 10,
        // 表格高度
        tableHeight: 0,
        // 用来存放日期组件所选中的值
        checkedTime: '',
        // 查询参数
        searchForm: {cname: null, cno: null, },
        // 弹出层
        dialog: {flag: 0, dialogTitle: "", visible: false, direction: 'rtl',size: '35%'},
        // 树形控件的属性绑定对象
		// 弹出层
		dialogTree: {treeProps: {children: 'children',label: 'cname'},defKeys: [],visible: false,},
        // 表单参数
        categoryForm: {
          categoryId: null,
          companyId: null,
          parentId: null,parentName: null,
		  cimg: null,
          cname: null,
          cno: null,
          pinyin: null,
          msg: null,
          seq: 1,
          status: 1,
        },
		// 裁切图片参数
		dialogImage: {cropperModel: false , cropperName: '' , cropperModel: false, },
        // 提交按钮文字
        loading: {status: false,BtnText: '确 定',SubText: '提交中...'},
        // 表单校验
        rules: {
          cname: [{required: true,trigger: "change",message: "请输入名称"}],
          cno: [{required: true,trigger: "change",message: "请输入编码"}],
        },
      };
    },
    mounted() {
      this.$nextTick(() => {
        this.tableHeight = window.innerHeight - 205;
      });
    },
    created() {
      this.getDataList();
    },
    watch: {
    },
    methods: {
		handleClose(done) {
		    this.resetForm();
		    done();
		},
      handleSizeChange(val) {
        this.pageSize = val;
        this.getDataList();
      },
      handleCurrentChange(val) {
        this.pageNum = val;
        this.getDataList();
      },
      // 获取列表
      getDataList() {
        category.list({cname: this.searchForm.cname,cno: this.searchForm.cno,}).then(res => {
          if(res.data.code === 2000) {
            this.tableData = res.data.data;
          }
        });
      },
      // 新增按钮操作
      openAdd() {
        this.dialog.flag = 0;
        this.resetForm("categoryForm");
        this.dialog.dialogTitle = "新增";
        this.dialog.visible = true;
		this.categoryForm.categoryId=null;this.categoryForm.parentId=null;
		this.categoryForm.parentName = null;
      },
      // 更新按钮操作
      openUpdate(row) {
        this.dialog.flag = 1;
        this.resetForm("categoryForm");
        this.dialog.dialogTitle = "编辑";
        this.dialog.visible = true;
        this.getById(row.categoryId);
      },
      // 提交数据操作
      submitFun() {
        this.$refs.categoryForm.validate(valid => {
          if(valid){
            this.loading.status = true;
            category.saveOrUpdate(this.categoryForm,this.dialog.flag).then(res => {
              if (res.data.code === 2000) {
                this.$message.success(res.data.msg);
                if(this.dialog.flag === 0){
                  this.pageNum = 1;
                }
                this.getDataList();
                // 关闭弹框
                this.dialog.visible = false;
                // 关闭加载
                this.loading.status = false;
              }else{
                this.$message.error(res.data.msg);
                this.loading.status = false;
                return false;
              }
            })
          }
        })
      },
      // 根据id获取信息
      getById(id) {
        category.getById(id).then(res => {
          if (res.data.code === 2000) {
            this.categoryForm.categoryId = res.data.data.categoryId;
            this.categoryForm.companyId = res.data.data.companyId;
            this.categoryForm.parentId = res.data.data.parentId;
			this.categoryForm.parentName = res.data.data.parentName;
            this.categoryForm.cname = res.data.data.cname;
            this.categoryForm.cno = res.data.data.cno;
            this.categoryForm.pinyin = res.data.data.pinyin;
            this.categoryForm.msg = res.data.data.msg;
            this.categoryForm.seq = res.data.data.seq;
            this.categoryForm.status = parseInt(res.data.data.status);
			this.categoryForm.cimg = res.data.data.cimg;
          }
        });
      },
      // 根据id删除
      deleteFun(row) {
        this.$confirm("确定删除当前吗？", "系统提示", {confirmButtonText: "确定", cancelButtonText: "取消", type: 'error'
        }).then(() =>{
            category.remove(row.categoryId).then(res => {
            if(res.data.code === 2000){
              this.$message.success(res.data.msg);
              this.getDataList()
            }else {
              this.$message.error(res.data.msg);
            }
          })
        }).catch(() => {
          this.$message.info("取消删除");
        });
      },
      // 清空表单
      resetForm(formName) {
        if (this.$refs[formName]) {
          this.$refs[formName].resetFields();
        }
      },
	  // 展示选择上级分类
	  catSelectDialogShow() {
	      // 默认选中根节点
		if(this.categoryForm.parentId == "0"){
			this.dialogTree.defKeys = [];
		}else{
			this.dialogTree.defKeys = [this.categoryForm.parentId];
		}
	      this.dialogTree.visible = true;
		  if(this.$refs.gcTreeRef){
			  this.$refs.gcTreeRef.setCheckedKeys([this.categoryForm.parentId]);
		  }
	  },
	  // 树组件单选实现
	  catHandleNodeClick(data, checked) {
	      if(checked === true) {
	          if(this.categoryForm.categoryId === data.categoryId) {
	              this.$message.warning("注意：禁止相同节点编辑，请选择其它节点");
	              this.$refs.gcTreeRef.setCheckedKeys([this.categoryForm.parentId]);
	          }else {
	              this.categoryForm.parentName = data.cname;
	              this.categoryForm.parentId = data.categoryId;
				  this.$refs.gcTreeRef.setCheckedKeys([data.categoryId]);
	          }
	      } else {
	          if (this.categoryForm.parentId === data.categoryId) {
	              this.$refs.gcTreeRef.setCheckedKeys([data.parentId]);
	          }
	      }
	  },
	  // 修改头像
	  uploadFun(name) {
	      this.dialogImage.cropperName = name;
	      this.dialogImage.cropperModel = true;
	  },
	  // 图片上传成功回调
	  handleUploadSuccess (data){
	      this.dialogImage.cropperModel = false;
	      this.categoryForm.cimg = data.url;
	  },
	  
    }
  }
</script>
<style lang="less" scoped>
  .el-search-item {margin-bottom: 0;}
  .el-card/deep/.el-card__body {padding: 0 10px 10px 10px !important;}
  .el-card/deep/.el-card__header {border-bottom: none !important;padding: 10px 10px !important;}
</style>